package com.example.forumadminbackend.service;

import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.file.*;
import java.util.*;

@Service
public class WordService {
    private static final String FILE_PATH = "words.txt";

    public List<String> getAllWords() throws IOException {
        File file = new File(FILE_PATH);
        if (!file.exists()) return new ArrayList<>();
        List<String> lines = Files.readAllLines(Paths.get(FILE_PATH));
        List<String> result = new ArrayList<>();
        for (String line : lines) {
            if (!line.trim().isEmpty()) {
                result.add(line.trim());
            }
        }
        return result;
    }

    private void writeWords(List<String> words) throws IOException {
        String content = String.join("\n", words);
        Files.write(Paths.get(FILE_PATH), content.getBytes());
    }

    public String addWord(String word) throws IOException {
        List<String> words = getAllWords();
        if (words.contains(word)) {
            return "该词已存在";
        } else {
            words.add(word);
            writeWords(words);
            return "添加成功";
        }
    }

    public String updateWord(String oldWord, String newWord) throws IOException {
        List<String> words = getAllWords();
        int idx = words.indexOf(oldWord);
        if (idx == -1) {
            return "未找到原违禁词";
        }
        if (words.contains(newWord)) {
            return "新词已存在";
        }
        words.set(idx, newWord);
        writeWords(words);
        return "修改成功";
    }

    public boolean deleteWord(String word) throws IOException {
        System.out.println("words.txt 绝对路径: " + new File(FILE_PATH).getAbsolutePath());
        List<String> words = getAllWords();
        boolean removed = words.removeIf(w -> w.trim().equals(word.trim()));
        if (removed) {
            writeWords(words);
        }
        return removed;
    }
} 